<template>
	<view class="horizontal-screen">
		<!-- k线图 -->
		<view ref="screenklinechart" class="k-line-container view-bg">
			<!-- <pei-chart :height="460" ref='ht0' :dataAs="chartData" canvasId="ht0" /> -->
			<!--  #ifdef  H5 -->
			<div>
				<div class='kline' id="kline" ref='kline'></div>
			</div>
			<!--  #endif -->
		
			<!--  #ifndef  H5 -->
			<view>
				<canvas id="kline2" canvas-id='kline2' class='kline2' v-bind:style="{width: ChartWidth+'px', height: ChartHeight+'px'}"
				 @touchstart="KLineTouchStart" @touchmove='KLineTouchMove' @touchend='KLineTouchEnd'></canvas>
			</view>
			<!--  #endif -->
		</view>
		<u-icon class="horizontal-icon" @click="back" name="close-circle" color="#fff" size="70"></u-icon>
	</view>
</template>

<script>
	// #ifdef H5
	import HQChart from '../../js_sdk/jones-hqchart/umychart_uniapp_h5/umychart.uniapp.h5.js'
	// #endif
	
	// #ifndef H5
	import {
		JSCommon
	} from '../../js_sdk/jones-hqchart/umychart.uniapp/umychart.wechat.3.0.js'
	import {
		JSCommonHQStyle
	} from '../../js_sdk/jones-hqchart/umychart.uniapp/umychart.style.wechat.js'
	// #endif
	
	HQChart.JSConsole.Chart.Log=function() { }  //不输出图形日志
	HQChart.JSConsole.Complier.Log=function() { }	//不输出指标脚本执行日志
	
	var pako = require('pako');
	
	function DefaultData() {}
	
	DefaultData.GetKLineOption = function() {
		let data = {
			Type: '历史K线图横屏',
	
			Windows: //窗口指标
				[{
						Index: "EMPTY",
						Modify: false,
						Change: false,
						TitleHeight: 0
					},
					// {Index:"VOL",Modify: false, Change: false}
				],
				
			IsClickShowCorssCursor:true,    //手势点击出现十字光标
			IsCorssOnlyDrawKLine:true,      //十字光标在K线中间
			CorssCursorTouchEnd:true,       //手势离开屏幕十字光标自动隐藏
			IsAutoUpdate: false, //是自动更新数据(不自动更新由外部更新)
			IsApiPeriod: true, //使用Api计算周期
	
			Border: //边框
			{
				Left: 1,
				Right: 1, //右边间距
				Top: 0,
				Bottom: 0,
			},
	
			KLine: {
				Right: 1, //复权 0 不复权 1 前复权 2 后复权
				Period: 4, //周期: 0 日线 1 周线 2 月线 3 年线 
				PageSize: 30,
				RightSpaceCount: 3,
				IsShowTooltip: false
			},
	
			Frame: //子框架设置
				[{
						SplitCount: 3, //Y轴3等份
						IsShowLeftText: false, //左侧不显示刻度文字
						SplitType: 1,
						Height: 8, //高度比值
						Custom: [{
							Type: 0,
							Position: 'right'
						}] //最新价格刻度
					},
	
					{
						SplitCount: 2, //Y轴2等份
						IsShowLeftText: false, //左侧不显示刻度文字
						SplitType: 1,
						Height: 2
					},
				],
			KLineTitle: {
				IsShowName: false,
				IsShowSettingInfo: false
			},
	
			ExtendChart: [{
					Name: 'KLineTooltip'
				}, //开启手机端tooltip
			],
	
		};
	
		return data;
	}
	
	var g_KLine = {
		JSChart: null
	};
	export default {
		data() {
			return {
				Symbol: 'btcusdt.BIT',
				OriginalSymbol: 'btcusdt',
				ChartWidth: 0,
				ChartHeight: 0,
				KLine: {
					Option: DefaultData.GetKLineOption(),
				},
				
				WSUrl: 'wss://api.huobiasia.vip/ws',
				SocketOpen: false,
				LastSubString: null, //最后一个订阅的数据
			}
		},
		onShow() {
			let _this = this;
			uni.getSystemInfo({
				success: (res) => {
					_this.$nextTick(() => {
						_this.OnSize();
						_this.CreateKLineChart();
					})
				}
			});
		
		},
		
		onHide() {
			if(this.SocketOpen)
			{
				uni.closeSocket();
				this.SocketOpen=false;
			}
			
			this.ClearChart();
		},
		
		onUnload() {
			if(this.SocketOpen)
			{
				uni.closeSocket();
				this.SocketOpen=false;
			}
			
			this.ClearChart();
		},
		methods: {
			back() {
				uni.switchTab({
					url: '/pages/period/index'
				})
			},
			//对外接口
			ChangePeriod(period) //周期切换
			{
				//var symbol=this.Symbol;
				g_KLine.JSChart.ChangePeriod(period);
			},
			
			ChangeSymbol(symbol) //切换股票
			{
				if (this.OriginalSymbol == symbol) return;
			
				this.OriginalSymbol = symbol;
				this.Symbol = symbol + '.BIT';
				g_KLine.JSChart.ChangeSymbol(this.Symbol);
			},
			
			OnSize() {
				// #ifdef H5
				this.OnSize_h5();
				// #endif
			},
			
			OnSize_h5() {
			
				let divKLineChart = this.$refs.screenklinechart.$el;
				this.ChartHeight = divKLineChart.offsetHeight;
				this.ChartWidth = divKLineChart.offsetWidth;
			
				let kline = this.$refs.kline;
				kline.style.width = this.ChartWidth + 'px';
				kline.style.height = this.ChartHeight + 'px';
				if (g_KLine.JSChart) g_KLine.JSChart.OnSize();
			},
			
			ClearChart()
			{
				if (g_KLine.JSChart)
				{
					g_KLine.JSChart.ChartDestory();
					g_KLine.JSChart=null;
				}
			
				// #ifdef H5
				var divKLine=document.getElementById('kline');
				while (divKLine.hasChildNodes()) 
				{
					divKLine.removeChild(divKLine.lastChild);
				}　
				// #endif
			},
			
			CreateKLineChart_h5() //创建K线图
			{
				if (g_KLine.JSChart) return;
			
				//黑色风格
				let blackStyle = HQChart.HQChartStyle.GetStyleConfig(HQChart.STYLE_TYPE_ID.BLACK_ID);
			
				blackStyle.BGColor = 'rgb(12,23,37)'; //背景
				blackStyle.FrameTitleBGColor = 'rgb(16,28,45)'; //指标标题背景
				blackStyle.FrameSplitTextColor = 'rgb(101,117,138)'; //刻度颜色
			
				//K线颜色
				blackStyle.UpBarColor = 'rgb(37,175,142)'; //K线上涨柱子颜色
				blackStyle.UpTextColor = blackStyle.UpBarColor; //上涨价格颜色
				blackStyle.DownBarColor = 'rgb(210,73,99)'; //K线下跌柱子颜色
				blackStyle.DownTextColor = blackStyle.DownBarColor; //下跌价格颜色
			
				//指标线段颜色
				blackStyle.Index.LineColor[0] = 'rgb(88,106,126)';
				blackStyle.Index.LineColor[1] = 'rgb(222,217,167)';
				blackStyle.Index.LineColor[2] = 'rgb(113,161,164)';
			
				//最新价格刻度颜色
				blackStyle.FrameLatestPrice.UpBarColor = 'rgb(37,175,142)';
				blackStyle.FrameLatestPrice.DownBarColor = 'rgb(210,73,99)';
			
				//面积图颜色
				blackStyle.CloseLineColor = 'rgb(113,121,133)'; //收盘价线颜色
				blackStyle.CloseLineAreaColor = ['rgba(36,41,57,0.8)', 'rgba(22,34,53,0.3)']; //收盘价面积图颜色
			
				//最高最低价颜色
				blackStyle.KLine.MaxMin.Color = 'rgb(255,250,240)';
			
				this.$refs.kline.style.backgroundColor = blackStyle.BGColor;
				HQChart.JSChart.SetStyle(blackStyle);
			
				this.KLine.Option.Symbol = this.Symbol;
				let chart = HQChart.JSChart.Init(this.$refs.kline);
				this.KLine.Option.NetworkFilter = this.NetworkFilter;
				chart.SetOption(this.KLine.Option);
				g_KLine.JSChart = chart;
			},
			
			CreateKLineChart_app() {
				if (g_KLine.JSChart) return;
			
				let element = new JSCommon.JSCanvasElement();
				// #ifdef APP-PLUS
				element.IsUniApp = true; //canvas需要指定下 是uniapp的app
				// #endif
				element.ID = 'kline2';
				element.Height = this.ChartHeight; //高度宽度需要手动绑定!!
				element.Width = this.ChartWidth;
			
				//var blackStyle=JSCommonHQStyle.GetStyleConfig(JSCommonHQStyle.STYLE_TYPE_ID.BLACK_ID);
				//JSCommon.JSChart.SetStyle(blackStyle);
			
				g_KLine.JSChart = JSCommon.JSChart.Init(element);
				this.KLine.Option.NetworkFilter = (data, callback) => {
					this.NetworkFilter(data, callback);
				};
				this.KLine.Option.Symbol = this.Symbol;
				this.KLine.Option.IsClickShowCorssCursor = true;
				this.KLine.Option.IsFullDraw = true; //每次手势移动全屏重绘
				g_KLine.JSChart.SetOption(this.KLine.Option);
			},
			
			CreateKLineChart() {
				// #ifdef H5
				this.CreateKLineChart_h5();
				// #endif
			
				// #ifndef H5
				this.CreateKLineChart_app();
				// #endif
			},
			
			NetworkFilter(data, callback) {
				// console.log('[KLineChart::NetworkFilter] data', data);
				switch (data.Name) {
					case 'KLineChartContainer::ReqeustHistoryMinuteData': //分钟全量数据下载
						this.RequestHistoryMinuteData(data, callback);
						break;
					case 'KLineChartContainer::RequestFlowCapitalData': //数字货币不会调用
						this.RequestFlowCapitalData(data, callback);
						break;
					case 'KLineChartContainer::RequestHistoryData': //日线全量数据下载
						this.RequestHistoryData(data, callback);
						break;
				}
			},
			
			//
			//WS
			//心跳包
			SendWSHeartMessage() {
				if (this.SocketOpen) {
					var pong = {
						'pong': new Date().getTime()
					};
					var message = JSON.stringify(pong);
					uni.sendSocketMessage({
						data: message
					});
				}
			},
			
			//取消订阅上一次的信息
			SendUnSubscribeMessage() {
				if (!this.LastSubString || !this.SocketOpen) return;
			
				var message = JSON.stringify({
					unsub: this.LastSubString
				}); //取消上次订阅的信息
				uni.sendSocketMessage({
					data: message
				});
				this.LastSubString = null; //清空最后一个订阅信息
			},
			
			RequestWSData(data, recvCallback) {
				if (!this.SocketOpen) {
					uni.connectSocket({
						url: this.WSUrl
					}); //创建连接
			
					uni.onSocketOpen((event) => {
						this.SocketOpen = true;
						// console.log(event);
						var message = JSON.stringify(data.SendData);
						uni.sendSocketMessage({
							data: message
						});
						if (data.SendData.sub) this.LastSubString = data.SendData.sub;
					});
				} else {
					this.SendUnSubscribeMessage();
					var message = JSON.stringify(data.SendData);
					uni.sendSocketMessage({
						data: message
					});
					if (data.SendData.sub) this.LastSubString = data.SendData.sub; //保存最后一个订阅信息
				}
			
				uni.onSocketMessage((event) => {
					let ploydata = new Uint8Array(event.data);
					let msg = pako.inflate(ploydata, {
						to: 'string'
					});
					//console.log("[KLineChart::RequestWSData] recv ", msg);
					var recvData = JSON.parse(msg);
					if (recvData.ping) {
						this.SendWSHeartMessage(); //回复服务器心跳包
					} else if (recvData.unsubbed) //取消订阅成功
					{
			
					} else if (recvData.subbed) //订阅成功 
					{
			
					} else {
						recvCallback(recvData, data);
					}
				});
			
				uni.onSocketError((evnet) => {
					console.log(event);
				});
			
			},
			
			//生成请求数据
			GeneratePostData(symbol, period) {
				//1min, 5min, 15min, 30min, 60min,4hour,1day,1week, 1mon
				var MAP_PERIOD = new Map([
					[4, '1min'],
					[5, '5min'],
					[6, "15min"],
					[0, '1day'],
					[1, '1week'],
					[2, '1mon'],
				]);
			
				var strPeriod = MAP_PERIOD.get(period);
			
				var reqData = {
					req: `market.${symbol}.kline.${strPeriod}`,
					symbol: symbol,
					period: strPeriod
				};
			
				var subData = {
					sub: `market.${symbol}.kline.${strPeriod}`,
					symbol: symbol,
					period: strPeriod
				};
			
				return {
					Req: reqData,
					Sub: subData
				};
			},
			
			//请求分钟历史数据
			RequestHistoryMinuteData(data, callback) {
				data.PreventDefault = true;
				var symbol = data.Request.Data.symbol;
				var period = data.Self.Period; //周期
			
				var postData = this.GeneratePostData(this.OriginalSymbol, period);
			
				var obj = {
					SendData: postData.Req,
					Symbol: symbol,
					OriginalSymbol: this.OriginalSymbol,
					Period: period,
					Callback: callback
				};
			
				this.RequestWSData(obj, (recvData, data) => {
					this.RecvHistoryMinuteData(recvData, data);
				});
			},
			
			//接收历史分钟数据
			RecvHistoryMinuteData(recvData, data) {
				if (recvData.rep != data.SendData.req) return;
			
				var hqChartData = {
					code: 0,
					data: []
				};
				hqChartData.symbol = data.Symbol;
				hqChartData.name = data.OriginalSymbol;
			
				if (recvData.data) {
					var yClose = null; //前收盘
					for (var i in recvData.data) {
						var item = recvData.data[i];
			
						//时间戳转换
						var dateTime = new Date();
						dateTime.setTime(item.id * 1000);
						var date = dateTime.getFullYear() * 10000 + (dateTime.getMonth() + 1) * 100 + dateTime.getDate();
						var time = dateTime.getHours() * 100 + dateTime.getMinutes();
			
						var newItem = [date, yClose, item.open, item.high, item.low, item.close, item.vol, item.amount, time];
			
						yClose = item.close;
						hqChartData.data.push(newItem);
					}
				}
			
				// #ifdef H5
				data.Callback(hqChartData);
				// #endif
			
				// #ifndef H5
				data.Callback({
					data: hqChartData
				});
				// #endif
			
				this.SubscribeMinuteRealtimeData(data);
			},
			
			//订阅最新分钟K线数据
			SubscribeMinuteRealtimeData(data) {
				//订阅最新数据
				var postData = this.GeneratePostData(data.OriginalSymbol, data.Period);
				var obj = {
					SendData: postData.Sub,
					Symbol: data.Symbol,
					OriginalSymbol: data.OriginalSymbol,
					Period: data.Period
				};
			
				this.RequestWSData(obj, (recvData, data) => {
					this.RecvMinuteRealtimeData(recvData, data);
				});
			},
			
			RecvMinuteRealtimeData(recvData, data) {
				if (recvData.ch != data.SendData.sub) return;
			
				var internalChart = g_KLine.JSChart.JSChartContainer;
				var period = internalChart.Period;
				var symbol = internalChart.Symbol;
				if (symbol != data.Symbol || period != data.Period) return;
			
				var hqChartData = {
					code: 0,
					data: [],
					ver: 2.0
				}; //更新数据使用2.0版本格式
				hqChartData.symbol = data.Symbol;
				hqChartData.name = data.OriginalSymbol;
			
				//TODO:把recvData => hqchart内部格式 格式看教程
				//HQChart使用教程30-K线图如何对接第3方数据15-轮询增量更新1分钟K线数据
			
				var item = recvData.tick;
			
				var dateTime = new Date();
				dateTime.setTime(item.id * 1000);
				var date = dateTime.getFullYear() * 10000 + (dateTime.getMonth() + 1) * 100 + dateTime.getDate();
				var time = dateTime.getHours() * 100 + dateTime.getMinutes();
				var newItem = [date, null, item.open, item.high, item.low, item.close, item.vol, item.amount, time];
			
				hqChartData.data.push(newItem);
			
				// #ifdef H5
				internalChart.RecvMinuteRealtimeData(hqChartData);
				// #endif
			
				// #ifndef H5
				internalChart.RecvMinuteRealtimeData({
					data: hqChartData
				});
				// #endif
			},
			
			
			//日K数据下载
			RequestHistoryData(data, callback) {
				data.PreventDefault = true;
				var symbol = data.Request.Data.symbol;
				var period = data.Self.Period; //周期
				var postData = this.GeneratePostData(this.OriginalSymbol, period);
			
				var obj = {
					SendData: postData.Req,
					Symbol: symbol,
					OriginalSymbol: this.OriginalSymbol,
					Period: period,
					Callback: callback
				};
			
				this.RequestWSData(obj, (recvData, data) => {
					this.RecvHistoryData(recvData, data);
				});
			},
			
			RecvHistoryData(recvData, data) //接收到日线数据 转化成hqchart格式数据
			{
				if (recvData.rep != data.SendData.req) return;
			
				var hqChartData = {
					code: 0,
					data: []
				};
				hqChartData.symbol = data.Symbol;
				hqChartData.name = data.OriginalSymbol;
			
				if (recvData.data) {
					var yClose = null; //前收盘
					for (var i in recvData.data) {
						var item = recvData.data[i];
			
						//时间戳转换
						var dateTime = new Date();
						dateTime.setTime(item.id * 1000);
						var date = dateTime.getFullYear() * 10000 + (dateTime.getMonth() + 1) * 100 + dateTime.getDate();
						var time = dateTime.getHours() * 100 + dateTime.getMinutes();
			
						var newItem = [date, yClose, item.open, item.high, item.low, item.close, item.vol, item.amount];
			
						yClose = item.close;
						hqChartData.data.push(newItem);
					}
				}
			
				// #ifdef H5
				data.Callback(hqChartData);
				// #endif
			
				// #ifndef H5
				data.Callback({
					data: hqChartData
				});
				// #endif
			
				this.SubscribRealtimeData(data);
			},
			
			//订阅最新日K线数据
			SubscribRealtimeData(data) {
				//订阅最新数据
				var postData = this.GeneratePostData(data.OriginalSymbol, data.Period);
			
				var obj = {
					SendData: postData.Sub,
					Symbol: data.Symbol,
					OriginalSymbol: data.OriginalSymbol,
					Period: data.Period
				};
			
				this.RequestWSData(obj, (recvData, data) => {
					this.RecvRealtimeData(recvData, data);
				});
			},
			
			RecvRealtimeData(recvData, data) {
				if (recvData.ch != data.SendData.sub) return;
			
				var internalChart = g_KLine.JSChart.JSChartContainer;
				var period = internalChart.Period;
				var symbol = internalChart.Symbol;
				if (symbol != data.Symbol || period != data.Period) return;
			
				var hqChartData = {
					code: 0,
					stock: []
				};
				//TODO:把recvData => hqchart内部格式 格式看教程
				//HQChart使用教程30-K线图如何对接第3方数据14-轮询增量更新日K数据
			
				var stock = {
					symbol: data.Symbol,
					name: data.OriginalSymbol
				};
				var item = recvData.tick;
				var dateTime = new Date();
				dateTime.setTime(item.id * 1000);
				var date = dateTime.getFullYear() * 10000 + (dateTime.getMonth() + 1) * 100 + dateTime.getDate();
				var time = dateTime.getHours() * 100 + dateTime.getMinutes();
			
				stock.date = date;
				stock.yclose = null;
				stock.open = item.open;
				stock.high = item.high;
				stock.low = item.low;
				stock.price = item.close;
				stock.vol = item.vol;
				stock.amount = item.amount;
			
				hqChartData.stock.push(stock);
			
				// #ifdef H5
				internalChart.RecvRealtimeData(hqChartData);
				// #endif
			
				// #ifndef H5
				internalChart.RecvRealtimeData({
					data: hqChartData
				});
				// #endif
			},
			
			
			///
			//手势事件 app/小程序才有
			//KLine事件
			KLineTouchStart: function(event) {
				if (g_KLine.JSChart) g_KLine.JSChart.OnTouchStart(event);
			},
			
			KLineTouchMove: function(event) {
				if (g_KLine.JSChart) g_KLine.JSChart.OnTouchMove(event);
			},
			
			KLineTouchEnd: function(event) {
				if (g_KLine.JSChart) g_KLine.JSChart.OnTouchEnd(event);
			}
		}
	}
</script>

<style lang="scss" scoped>
	uni-page-body {
		height: 100%;
	}
	.horizontal-screen {
		height: 100%;
		position: relative;
		
		.k-line-container {
			width: 100%;
			height: 100%;
		}
		
		.horizontal-icon {
			position: absolute;
			right: 40rpx;
			bottom: 40rpx;
			z-index: 11111;
		}
	}
</style>
